package com.haochen.springboot.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.security.Principal;

/**
 * @Author: zhuoli
 * @Date: 2018/4/19 11:32
 * @Description:
 */
@Controller
public class HelloController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/hello")
    @PreAuthorize("hasRole('ADMIN')")
    public String hello(ModelMap map, Principal principal1) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String username = "";
        if (principal instanceof UserDetails) {
            username = ((UserDetails)principal).getUsername();
        } else {
            username = principal.toString();
        }
        map.put("username", username);
        System.out.println("java后端代码获取：" + username);
        System.out.println("请求传值" + principal1.getName());
        return "hello";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }
}
